package cn.gdrj.est.service.impl;

import cn.gdrj.est.dao.ModelDao;
import cn.gdrj.est.dto.ModelDTO;
import cn.gdrj.est.dto.ModelDetailDTO;
import cn.gdrj.est.dto.PageResult;
import cn.gdrj.est.entity.Model;
import cn.gdrj.est.service.ModelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO(这里用一句话描述这个类的作用)
 *
 * @author jun
 * @date 2021/11/5
 */
@Service
public class ModelServiceImpl implements ModelService {
    @Autowired
    private ModelDao modelDao;
    @Value("${oss.aliyun.url}")
    private String ossUrl;

    @Override
    public ModelDetailDTO getById(Long id) {
        Model model = modelDao.selectByPrimaryKey(id);
        if(ObjectUtils.isEmpty(model)){
            return null;
        }

        ModelDetailDTO modelDetailDTO = new ModelDetailDTO();
        BeanUtils.copyProperties(model,modelDetailDTO);
        modelDetailDTO.setFaceImg(ossUrl + modelDetailDTO.getFaceImg());
        modelDetailDTO.setContentImg(ossUrl + modelDetailDTO.getContentImg());
        return modelDetailDTO;
    }

    @Override
    public List<ModelDTO> listBy(Model model, int pageIndex, int pageSize) {
        int offset = (pageIndex - 1) * pageSize;
        List<Model> models = modelDao.listByPage(model, offset, pageSize);

        List<ModelDTO> modelDTOS = new ArrayList<>();
        for (Model m : models) {
            ModelDTO dto = new ModelDTO();
            BeanUtils.copyProperties(m, dto);
            dto.setFaceImg(ossUrl + dto.getFaceImg());
            modelDTOS.add(dto);
        }
        return modelDTOS;
    }

    @Override
    public PageResult<ModelDTO> listByPage(Model model,
                                           int pageIndex,
                                           int pageSize) {
        // 查询符合条件的记录数
        int count = modelDao.countBy(model);
        PageResult<ModelDTO> pageResult = new PageResult<>(5, count);
        pageResult.setPageNo(pageIndex);
        if (count == 0) {
            return pageResult;
        }
        // 查询符合条件的数据
        List<ModelDTO> modelDTOS = this.listBy(model, pageIndex, pageSize);
        pageResult.setList(modelDTOS);
        return pageResult;
    }
}
